import { Sighting } from '../models/Sighting.js';
import { Post } from '../models/Post.js';
import { 
  successResponse, 
  errorResponse, 
  notFoundResponse,
  forbiddenResponse,
  paginatedResponse,
  validationErrorResponse,
  tooManyRequestsResponse 
} from '../utils/response.js';
import { getFileUrl, deleteFile } from '../utils/upload.js';

/**
 * 提交目击线索或评论（匿名）
 */
export async function submitSighting(req, res) {
  try {
    const { post_id, sighting_location } = req.body;
    const reporterIP = req.ip || req.connection.remoteAddress;

    // 检查帖子是否存在且已审核通过
    const post = await Post.findById(post_id);
    if (!post) {
      return notFoundResponse(res, '帖子不存在');
    }

    if (post.admin_status !== 'approved') {
      return forbiddenResponse(res, '该帖子尚未审核通过');
    }

    // 判断是线索还是评论
    const isComment = sighting_location && sighting_location.startsWith('COMMENT:');

    // 如果是线索，检查帖子状态
    if (!isComment && post.post_status !== 'searching') {
      return forbiddenResponse(res, '该帖子已不再接受线索');
    }

    // 防止滥用：检查同一IP在24小时内提交的数量
    const recentSightings = await Sighting.countRecentByIP(reporterIP, 24);
    const maxSubmissions = isComment ? 20 : 10; // 评论限制更宽松
    if (recentSightings >= maxSubmissions) {
      const type = isComment ? '评论' : '线索';
      return tooManyRequestsResponse(res, `您今天提交的${type}过多，请明天再试`);
    }

    const sightingData = {
      ...req.body,
      reporter_ip: reporterIP
    };

    // 如果有上传的照片，设置照片URL
    if (req.file) {
      sightingData.sighting_photo_url = getFileUrl(req.file.filename, 'sightings');
    }

    const newSighting = await Sighting.create(sightingData);

    // TODO: 发送通知给帖子作者

    const type = isComment ? '评论' : '线索';
    const message = isComment ? '感谢您的评论！' : '感谢您提供线索！线索已提交给宠物主人。';

    return successResponse(res, {
      id: newSighting.id,
      message
    }, `${type}提交成功`, 201);

  } catch (error) {
    console.error('提交失败:', error);

    // 如果提交失败且有上传的文件，删除文件
    if (req.file) {
      await deleteFile(`uploads/sightings/${req.file.filename}`);
    }

    return errorResponse(res, '提交失败，请稍后重试', 500);
  }
}

/**
 * 获取帖子的线索列表（公开访问）
 */
export async function getPostSightingsPublic(req, res) {
  try {
    const postId = parseInt(req.params.postId);

    if (isNaN(postId)) {
      return validationErrorResponse(res, [{ field: 'postId', message: '无效的帖子ID' }]);
    }

    // 检查帖子是否存在且已审核通过
    const post = await Post.findById(postId);
    if (!post) {
      return notFoundResponse(res, '帖子不存在');
    }

    if (post.admin_status !== 'approved') {
      return forbiddenResponse(res, '该帖子尚未审核通过');
    }

    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;

    const sightings = await Sighting.findByPostId(postId, { page, limit });
    const total = await Sighting.countByPostId(postId);

    return paginatedResponse(res, sightings.map(sighting => sighting.toJSON()), {
      page,
      limit,
      total
    }, '获取线索列表成功');

  } catch (error) {
    console.error('获取线索列表失败:', error);
    return errorResponse(res, '获取线索列表失败，请稍后重试', 500);
  }
}

/**
 * 获取帖子的线索列表（仅帖子作者可见）
 */
export async function getPostSightings(req, res) {
  try {
    const postId = parseInt(req.params.postId);
    const userId = req.user.id;

    if (isNaN(postId)) {
      return validationErrorResponse(res, [{ field: 'postId', message: '无效的帖子ID' }]);
    }

    // 检查帖子是否存在
    const post = await Post.findById(postId);
    if (!post) {
      return notFoundResponse(res, '帖子不存在');
    }

    // 检查帖子是否属于当前用户
    const belongsToUser = await Post.belongsToUser(postId, userId);
    if (!belongsToUser) {
      return forbiddenResponse(res, '您没有权限查看此帖子的线索');
    }

    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;

    const sightings = await Sighting.findByPostId(postId, { page, limit });
    const total = await Sighting.countByPostId(postId);

    return paginatedResponse(res, sightings.map(sighting => sighting.toJSON()), {
      page,
      limit,
      total
    }, '获取线索列表成功');

  } catch (error) {
    console.error('获取线索列表失败:', error);
    return errorResponse(res, '获取线索列表失败，请稍后重试', 500);
  }
}

/**
 * 根据ID获取线索详情（仅帖子作者可见）
 */
export async function getSightingById(req, res) {
  try {
    const sightingId = parseInt(req.params.id);
    const userId = req.user.id;
    
    if (isNaN(sightingId)) {
      return validationErrorResponse(res, [{ field: 'id', message: '无效的线索ID' }]);
    }

    const sighting = await Sighting.findById(sightingId);
    
    if (!sighting) {
      return notFoundResponse(res, '线索不存在');
    }

    // 检查线索对应的帖子是否属于当前用户
    const belongsToUser = await Post.belongsToUser(sighting.post_id, userId);
    if (!belongsToUser) {
      return forbiddenResponse(res, '您没有权限查看此线索');
    }

    return successResponse(res, sighting.toJSON(), '获取线索详情成功');

  } catch (error) {
    console.error('获取线索详情失败:', error);
    return errorResponse(res, '获取线索详情失败，请稍后重试', 500);
  }
}

/**
 * 验证线索（标记为有效/无效）
 */
export async function verifySighting(req, res) {
  try {
    const sightingId = parseInt(req.params.id);
    const userId = req.user.id;
    const { is_verified } = req.body;
    
    if (isNaN(sightingId)) {
      return validationErrorResponse(res, [{ field: 'id', message: '无效的线索ID' }]);
    }

    const sighting = await Sighting.findById(sightingId);
    
    if (!sighting) {
      return notFoundResponse(res, '线索不存在');
    }

    // 检查线索对应的帖子是否属于当前用户
    const belongsToUser = await Post.belongsToUser(sighting.post_id, userId);
    if (!belongsToUser) {
      return forbiddenResponse(res, '您没有权限验证此线索');
    }

    const updatedSighting = await Sighting.updateVerificationStatus(sightingId, is_verified);

    const message = is_verified ? '线索已标记为有效' : '线索已标记为无效';

    return successResponse(res, updatedSighting.toJSON(), message);

  } catch (error) {
    console.error('验证线索失败:', error);
    return errorResponse(res, '验证线索失败，请稍后重试', 500);
  }
}

/**
 * 获取所有线索列表（管理员用）
 */
export async function getAllSightings(req, res) {
  try {
    const { is_verified, post_id } = req.query;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;

    const filters = {};
    if (is_verified !== undefined) {
      filters.is_verified = is_verified === 'true';
    }
    if (post_id) {
      filters.post_id = parseInt(post_id);
    }

    const sightings = await Sighting.findAll(filters, { page, limit });
    const total = await Sighting.count(filters);

    return paginatedResponse(res, sightings.map(sighting => sighting.toJSON(true)), {
      page,
      limit,
      total
    }, '获取线索列表成功');

  } catch (error) {
    console.error('获取线索列表失败:', error);
    return errorResponse(res, '获取线索列表失败，请稍后重试', 500);
  }
}

/**
 * 删除线索（管理员用）
 */
export async function deleteSighting(req, res) {
  try {
    const sightingId = parseInt(req.params.id);
    
    if (isNaN(sightingId)) {
      return validationErrorResponse(res, [{ field: 'id', message: '无效的线索ID' }]);
    }

    // 检查线索是否存在
    const existingSighting = await Sighting.findById(sightingId);
    if (!existingSighting) {
      return notFoundResponse(res, '线索不存在');
    }

    // 删除线索照片
    if (existingSighting.sighting_photo_url) {
      const photoPath = existingSighting.sighting_photo_url.replace('/', '');
      await deleteFile(photoPath);
    }

    const success = await Sighting.delete(sightingId);
    
    if (!success) {
      return errorResponse(res, '删除线索失败', 500);
    }

    return successResponse(res, null, '线索删除成功');

  } catch (error) {
    console.error('删除线索失败:', error);
    return errorResponse(res, '删除线索失败，请稍后重试', 500);
  }
}

/**
 * 上传线索照片
 */
export async function uploadSightingPhoto(req, res) {
  try {
    if (!req.file) {
      return validationErrorResponse(res, [{ field: 'photo', message: '请选择要上传的照片' }]);
    }

    const photoUrl = getFileUrl(req.file.filename, 'sightings');

    return successResponse(res, {
      photo_url: photoUrl,
      filename: req.file.filename,
      size: req.file.size,
      mimetype: req.file.mimetype
    }, '照片上传成功');

  } catch (error) {
    console.error('上传照片失败:', error);
    
    // 如果处理失败，删除已上传的文件
    if (req.file) {
      await deleteFile(`uploads/sightings/${req.file.filename}`);
    }
    
    return errorResponse(res, '照片上传失败，请稍后重试', 500);
  }
}

/**
 * 获取线索统计信息（管理员用）
 */
export async function getSightingStats(req, res) {
  try {
    const stats = await Sighting.getStats();

    return successResponse(res, stats, '获取线索统计成功');

  } catch (error) {
    console.error('获取线索统计失败:', error);
    return errorResponse(res, '获取线索统计失败，请稍后重试', 500);
  }
}
